angular.module('app.controllers', [])

    .controller('mainCtrl', function ($scope, $state, $ionicModal, $ionicHistory, SystemService, $timeout, UserService) {

        console.log('mainCtrl')
        $scope.$on('$ionicView.enter', function (e) {
        });

        $scope.loginData = {};
        $scope.showloginpwd = false;
        $ionicModal.fromTemplateUrl('templates/main/login.html', {
            scope: $scope
        }).then(function (modal) {
            $scope.loginModal = modal;
        });


        $scope.closeLogin = function () {
            $scope.loginModal.hide();
        };

        $scope.login = function () {
            $scope.loginModal.show();
        };

        $scope.doLogin = function () {


            if (JSON.stringify($scope.loginData) == '{}' || $scope.loginData.studentID == '' || $scope.loginData.pwdText == '') {

                console.log($scope.time)
                swal({
                    title: '出错啦!',
                    text: '账号密码不能为空',
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {
                });
            }
            else {

                let promise = UserService.login($scope.loginData);
                promise.then(function (data) {
                    console.log(data.name);
                    swal('成功!', '登录成功', 'success');
                    $scope.closeLogin();
                    if (data.name == "admin") {
                        let admin = true;
                        $state.go('app.showTimeForAll');
                    }
                    else {
                        let admin = false;
                        $state.go('app.home');
                    }
                }, function (err) {
                    swal({
                        title: '出错啦!',
                        text: err,
                        timer: 800,
                        type: 'error',
                        showConfirmButton: false
                    }).catch(() => {
                    });
                });
            }


        };

        $scope.registerData = {};
        $scope.showregisterpwd = false;
        $ionicModal.fromTemplateUrl('templates/main/register.html', {
            scope: $scope
        }).then(function (modal) {
            $scope.registerModal = modal;
        });

        $scope.closeRegister = function () {
            $scope.registerModal.hide();
        };

        $scope.register = function () {
            $scope.registerModal.show();
        };

        $scope.doRegister = function () {
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;


            if (JSON.stringify($scope.registerData) == '{}' || $scope.registerData.name == "" || $scope.registerData.pwd == "") {

                swal({
                    title: '出错啦!',
                    text: '用户名名或密码为空，请重新输入！',
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {
                });
            }
            else if ($scope.registerData.pwdText != $scope.registerData.pwdText2) {
                swal({
                    title: '出错啦!',
                    text: '密码不一致',
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {
                });

            }

            else if (!filter.test($scope.registerData.email)) {

                swal({
                    title: '出错啦!',
                    text: '邮箱格式不正确',
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {
                });


            }
            else if ($scope.registerData.mobile.length != 11) {
                swal({
                    title: '出错啦!',
                    text: '手机格式不正确',
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {
                });

            }
            else {
                console.log($scope.registerData)
                let promise = UserService.register($scope.registerData);
                promise.then(function (data) {
                    console.log(data);

                    console.log($scope.doSignup);

                    swal({
                        title: '成功！',
                        text: '登录成功',
                        timer: 800,
                        type: 'success',
                        showConfirmButton: false
                    }).catch(() => {
                    });
                    $scope.closeRegister();
                    if (data.isAdmin) {
                        $state.go('app.showTimeForAll');
                    }
                    else {
                        $state.go('app.home');
                    }
                }, function (err) {
                    swal({
                        title: '出错啦!',
                        text: err,
                        timer: 800,
                        type: 'error',
                        showConfirmButton: false
                    }).catch(() => {
                    });


                });
            }

        };


        $scope.resetPwdData = {};

        $ionicModal.fromTemplateUrl('templates/main/resetPwd.html', {
            scope: $scope
        }).then(function (modal) {
            $scope.resetPwdModal = modal;
        });

        $scope.closeResetPwd = function () {
            $scope.resetPwdModal.hide();
        };

        $scope.resetPwd = function () {
            $scope.resetPwdModal.show();
        };

        $scope.doResetPwd = function () {

            let promise = UserService.doResetPwd($scope.resetPwdData.resetPwd, $scope.resetPwdData.resetPwd2);
            promise.then(function (data) {
                console.log(data);
                // $scope.showtime = data[0]

                // console.log($scope.Keep);

                swal('成功!', '保存成功', 'success');
                $ionicHistory.goBack();
            }, function (err) {
                swal({
                    title: '出错啦!',
                    text: err,
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {
                });
            });


        };
    })

    .controller('AppCtrl', function ($scope, $state, $ionicHistory, $ionicModal, $timeout, SystemService, UserService) {
        console.log('AppCtrl');
        $scope.$on('$ionicView.enter', function () {
            let promise = UserService.getInformation();
            promise.then(function (data) {

                if (data.isAdmin) {
                    $scope.admin = true;
                }
                else {
                    $scope.admin = false;
                }
            }, function (err) {
                swal("抱歉,无法完成操作", err, "warning");
            });

        });


        $scope.logout = function () {
            swal('成功!', '已登出', 'success');
            $ionicHistory.clearHistory();
            $state.go('main');
        };
    })


    .controller('homeCtrl', function ($scope) {
        console.log('home');
    })

    .controller('aboutCtrl', function ($scope) {
        console.log('aboutCtrl')

    })

    .controller('userCtrl', function ($scope, SystemService, UserService) {
        console.log('userCtrl')

        let promise = UserService.getInformation();


        promise.then(function (data) {

            if (data) {
                console.log(data);
                console.log(data.mobile);
                $scope.mobile = data.mobile;
                $scope.name = data.name;
                $scope.studentID = data.studentID;
                $scope.email = data.email;
                $scope.sex = data.sex;

            }

        }, function (err) {
            swal("抱歉,无法完成操作", err, "warning");
        });


    })

    .controller('showtimeCtrl', function ($rootScope, $scope, UserService, SystemService, $ionicNavBarDelegate, $ionicHistory) {
        console.log('showtimeCtrl')

        $scope.week = ['Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'];
        $scope.isMorningTime = [];
        $scope.isAfternoonTime = [];
        $scope.isEveningTime = [];
        $scope.timetable = {
            Mon: {
                MorningStart: "",
                MorningEnd: "",
                AfternoonStart: "",
                AfternoonEnd: "",
                EveningStart: "",
                EveningEnd: "",
            },
            Tue: {
                MorningStart: "",
                MorningEnd: "",
                AfternoonStart: "",
                AfternoonEnd: "",
                EveningStart: "",
                EveningEnd: "",
            },
            Wed: {
                MorningStart: "",
                MorningEnd: "",
                AfternoonStart: "",
                AfternoonEnd: "",
                EveningStart: "",
                EveningEnd: "",
            },
            Thur: {
                MorningStart: "",
                MorningEnd: "",
                AfternoonStart: "",
                AfternoonEnd: "",
                EveningStart: "",
                EveningEnd: "",
            },
            Fri: {
                MorningStart: "",
                MorningEnd: "",
                AfternoonStart: "",
                AfternoonEnd: "",
                EveningStart: "",
                EveningEnd: "",
            },
            Sat: {
                MorningStart: "",
                MorningEnd: "",
                AfternoonStart: "",
                AfternoonEnd: "",
                EveningStart: "",
                EveningEnd: "",
            },
            Sun: {
                MorningStart: "",
                MorningEnd: "",
                AfternoonStart: "",
                AfternoonEnd: "",
                EveningStart: "",
                EveningEnd: "",
            },
        }

        $scope.$on('$ionicView.enter', function () {
            let promise = UserService.getTimeTable();

            promise.then(function (data) {
                console.log(data.timetable);
                console.log(data.timetable.Mon.MorningStart);
                if (data && data.timetable) {
                    $scope.timetable = data.timetable;

                    for (var i = 0; i < 7; i++) {
                        if ($scope.timetable[$scope.week[i]].MorningStart && $scope.timetable[$scope.week[i]].MorningEnd) {
                            $scope.isMorningTime[i] = true;
                        }
                        else {
                            $scope.isMorningTime[i] = false;
                        }
                        if ($scope.timetable[$scope.week[i]].AfternoonStart && $scope.timetable[$scope.week[i]].AfternoonEnd) {
                            $scope.isAfternoonTime[i] = true;
                        }
                        else {
                            $scope.isAfternoonTime[i] = false;
                        }
                        if ($scope.timetable[$scope.week[i]].EveningStart && $scope.timetable[$scope.week[i]].EveningEnd) {
                            $scope.isEveningTime[i] = true;
                        }
                        else {
                            $scope.isEveningTime[i] = false;
                        }
                    }


                }
            }, function (err) {
                swal("抱歉,无法完成操作", err, "warning");
            });

        });


    })


    .controller('weekCtrl', function ($scope, SystemService, $ionicHistory, UserService) {

            $scope.time = {};
            $scope.Keep = function (weekday) {

                var isCorrect = false;

                if (/^(?:[01]?\d|2[0-4]):(?:[0-5]?\d|60)$/.test($scope.time.mons) || $scope.time.mons == null) {

                    if (/^(?:[01]?\d|2[0-4]):(?:[0-5]?\d|60)$/.test($scope.time.mone) || $scope.time.mone == null) {
                        if (/^(?:[01]?\d|2[0-4]):(?:[0-5]?\d|60)$/.test($scope.time.afts) || $scope.time.afts == null) {
                            if (/^(?:[01]?\d|2[0-4]):(?:[0-5]?\d|60)$/.test($scope.time.afte) || $scope.time.afte == null) {
                                if (/^(?:[01]?\d|2[0-4]):(?:[0-5]?\d|60)$/.test($scope.time.eves) || $scope.time.eves == null) {
                                    if (/^(?:[01]?\d|2[0-4]):(?:[0-5]?\d|60)$/.test($scope.time.evee) || $scope.time.evee == null) {
                                        isCorrect = true;
                                    }
                                }
                            }
                        }
                    }
                }

                if (isCorrect == true) {
                    console.log($scope.time);
                    let promise = UserService.Keep($scope.time, weekday);
                    promise.then(function (data) {
                        console.log(data);
                        swal('成功!', '保存成功', 'success');

                        $ionicHistory.goBack();
                    }, function (err) {
                        swal({
                            title: '出错啦!',
                            text: err,
                            timer: 800,
                            type: 'error',
                            showConfirmButton: false
                        }).catch(() => {
                        });
                    });
                }
                else {
                    console.log(isCorrect);
                    swal({
                        title: '出错啦!',
                        text: "时间格式错误",
                        timer: 800,
                        type: 'error',
                        showConfirmButton: false
                    }).catch(() => {
                    });
                }

            };

        }
    )
    .controller('showTimeForAllCtrl', function ($scope, AdminService) {
    })

    .controller('showTimeForAllCtrl', function ($scope, $state, UserService) {
        $scope.week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
        $scope.toDay = function (weekday) {
            $state.go('app.showTimeForDay', {weekday: weekday});
        }
    })
    .controller('showTimeForDayCtrl', function ($scope, $state, AdminService, $stateParams) {
        $scope.weekday = $stateParams.weekday;
        $scope.period = ['Morning', 'Afternoon', 'Evening'];
        $scope.toPeriod = function (weekday, period) {
            $state.go('app.showTimeForPeriod', {
                args: {
                    weekday: weekday,
                    period: period
                }
            })
        }

    })
    .controller('showTimeForPeriodCtrl', function ($scope, AdminService, $stateParams, UserService) {
        $scope.weekday = $stateParams.args.weekday;
        $scope.period = $stateParams.args.period;
        $scope.periodStart=$scope.period+"Start";

        let promise = AdminService.getStudentMessage($scope.weekday,$scope.periodStart);
        promise.then(function (data) {

            if (data) {
                console.log(data);
                $scope.user=data;
            }

        }, function (err) {
            swal("抱歉,无法完成操作", err, "warning");
            console.log("happy");
        });


        $scope.showTime = function () {
            //根据studentID、weekday、period查询学生在该时间段的开始时间和结束时间
            swal({
                title: '时间',
                /*text: $scope.weekday.period.morningStart-$scope.weekday.period.morningEnd*/
                text: $scope.morningStart
            })
        }
    })


    .controller('GroupAdminCtrl', function ($scope, AdminService, $state) {

        $scope.$on('$ionicView.enter', function () {
            let promise = AdminService.getName();
            promise.then(function (data) {
                console.log(data);
                $scope.groups = data;

            })
        });

        $scope.show = function (group) {

            console.log('show');
            $state.go('app.groupMember', group);
            console.log(group)

        };

        $scope.edit = function (group) {

            console.log('edit');
            swal({
                title: '请输入更改后的组名',
                type: 'info',
                input: 'text',
                inputPlaceholder: "你的组名",
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(function (inputValue) {
                let promise = AdminService.editGroupName(group,inputValue);
                promise.then(function (data) {
                    let promise = AdminService.getName();
                    promise.then(function (data) {
                        $scope.groups = data;
                    })

                },function(err){
                    swal("出错啦",err,"error");
                })

            },function (dismiss) {
                if (dismiss === 'cancel') {
                    // ignore
                } else {
                    console.log(dismiss);
                }
            });
            console.log(1)

        };

        $scope.addGroup = function (){
            swal({
                title: '请输入组名',
                type: 'info',
                input: 'text',
                inputPlaceholder: "你的组名",
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(function (inputValue) {
                let promise = AdminService.add(inputValue);
                promise.then(function (data) {
                    let promise = AdminService.getName();
                    promise.then(function (data) {
                        console.log(data);
                        $scope.groups = data;

                    })
                },function (err) {
                    swal("出错啦",err,"error")
                })

            }, function (dismiss) {
                if (dismiss === 'cancel') {
                    // ignore
                } else {
                    console.log(dismiss);
                }
            });

        };

    })

    .controller('addGroupCtrl', function ($scope, AdminService, $state, $ionicHistory) {
        $scope.AddUserData = {};

        $scope.back = function () {
            $ionicHistory.goBack();
        }

        $scope.doAdd = function () {
            let promise = AdminService.add($scope.AddUserData);
            promise.then(function (data) {
                console.log(data);
                swal({
                    title: '成功！',
                    text: '添加成功',
                    timer: 800,
                    type: 'success',
                    showConfirmButton: false
                }).catch(() => {
                });
            }, function (err) {
                swal({
                    title: '出错了！',
                    text: err,
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {


                });

            })
        }


    })
    .controller('deleteGroupCtrl', function ($scope, AdminService, $ionicHistory, $state) {

        $scope.$on('$ionicView.enter', function () {
            console.log(123456);
            let promise = AdminService.getName();
            promise.then(function (data) {
                $scope.groups = data;
            })
        });
        $scope.back = function () {
            $ionicHistory.goBack();
        }
        $scope.data = {
            showDelete: false
        };

        $scope.onGroupDelete = function (group) {
            $scope.groups.splice($scope.groups.indexOf(group), 1);
            let promise = AdminService.delete(group);
            promise.then(function (data) {
                console.log(data);
                swal({
                    title: '成功！',
                    text: '删除成功',
                    timer: 800,
                    type: 'success',
                    showConfirmButton: false
                }).catch(() => {
                });
            }, function (err) {
                swal({
                    title: '出错了！',
                    text: err,
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {});
            });
        }
    })
    .controller('groupMemberCtrl',function($scope, GroupMemberService, $ionicHistory, $state,$stateParams){

        $scope.$on("$ionicView.beforeEnter",function () {
            console.log($stateParams);
            let promise = GroupMemberService.getGroupMembers($stateParams);
            promise.then(function (data) {
                $scope.members = data;
            })
        });

        $scope.deleteMember = function(member){
            let group = $stateParams;
            let promise = GroupMemberService.deleteGroupMember(group,member);
            promise.then(function (data) {
                console.log(data);
                swal({
                    title: '成功！',
                    text: '删除成功',
                    timer: 800,
                    type: 'success',
                    showConfirmButton: false
                }).catch(() => {
                });
            }, function (err) {
                swal({
                    title: '出错了！',
                    text: err,
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {});
            });


        };

        $scope.addMember = function(){

            $state.go('app.addGroupMember',$stateParams);


        };





    })
    .controller('addGroupMemberCtrl',function($scope, GroupMemberService, $ionicHistory, $state,$stateParams){

        $scope.$on("$ionicView.beforeEnter",function () {
            console.log($stateParams);
            let promise = GroupMemberService.getNotMember($stateParams);
            promise.then(function (data) {
                console.log(data)
                $scope.members = data;
            })
        });

        // $scope.addGroupMember = function(member){};

        $scope.addGroupMember = function(member){
            let group = $stateParams;
            let promise = GroupMemberService.addGroupMember(group,member);
            promise.then(function (data) {
                console.log(data);
                swal({
                    title: '成功！',
                    text: '添加成功',
                    timer: 800,
                    type: 'success',
                    showConfirmButton: false
                }).catch(() => {
                });
            }, function (err) {
                swal({
                    title: '出错了！',
                    text: err,
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {});
            });


        };


    })

    .controller('tagCtrl', function ($scope, MusicTagService, $rootScope,$ionicHistory, $state, $stateParams) {
        $scope.music = {
            "第一层": [
                "流行",
                "摇滚",
                "民谣",
                "电子",
                "舞曲",
                "轻音乐",
                "爵士",
                "乡村",
                "R&B/Soul节奏布鲁斯",
                "古典",
                "民族",
                "英伦",
                "金属",
                "朋克",
                "蓝调",
                "雷鬼",
                "拉丁",
                "另类",
                "New Age",
                "古风",
                "后摇",
                "Bossa Nova",
                "儿童",
                "动漫"
            ],
            "第二层": [
                "喜",
                "怒",
                "哀",
                "乐",
                "惊",
                "恐",
                "思"
            ],
            "第三层": [

                "喜爱",
                "喜悦",

                "愤怒",
                "怨恨",

                "悲伤",
                "哀怨",
                "哀思",

                "欢乐",

                "惊咤",
                "惊喜",
                "恐惧",
                "担忧",

                "想念",
                "思慕"

            ],
            "第四层": {
                "喜爱": [
                    "浪漫",
                    "美好",
                    "温暖",
                    "轻快",
                    "甜蜜"
                ],
                "喜悦": [
                    "清新",
                    "欢快",
                    "轻快",
                    "快乐",
                    "放松"
                ],
                "愤怒": [
                    "治愈",
                    "安静",
                    "放松",
                    "清新"
                ],
                "怨恨": [
                    "温暖",
                    "治愈",
                    "清新",
                    "放松"
                ],
                "悲伤": [
                    "治愈",
                    "安静",
                    "怀旧",
                    "温暖"
                ],
                "哀怨": [
                    "幸福",
                    "感动",
                    "快乐",
                    "治愈"
                ],
                "哀思": [
                    "孤独",
                    "安静",
                    "怀旧"
                ],
                "欢乐": [
                    "欢快",
                    "轻快",
                    "放松",
                    "性感"
                ],
                "惊诧": [
                    "放松",
                    "安静",
                    "清新",
                    "美好"
                ],
                "惊喜": [
                    "快乐",
                    "欢快",
                    "美好",
                    "甜蜜",
                    "性感"
                ],
                "恐惧": [
                    "治愈",
                    "温暖",
                    "放松",
                    "幸福"
                ],
                "担忧": [
                    "放松",
                    "安静",
                    "轻快",
                    "清新"
                ],
                "想念": [
                    "怀旧",
                    "感动",
                    "浪漫",
                    "甜蜜"
                ],
                "思慕": [
                    "感动",
                    "美好",
                    "怀旧",
                    "孤独"
                ]
            }
        };
        let tag1s = $scope.music['第一层'];
        let data = new Array(tag1s.length);
        console.log(tag1s.length)
        $scope.data = data;
        for (let i = 0; i < data.length; i++) {
            data[i] = false;
        }
        let chooseTag1 = [];
        $scope.chooseOne = function (one, i) {
            data[i] = !data[i];
            chooseTag1 = [];
            for (let i = 0; i < data.length; i++) {
                if (data[i]) {
                    chooseTag1.push(tag1s[i]);
                }
            }
            console.log(chooseTag1);
        }


        let tag2 = $scope.music['第二层'];
        let data2 = new Array(tag2.length);
        console.log(tag2.length)
        $scope.data2 = data2;
        for (let j = 0; j < data2.length; j++) {
            data2[j] = false;
        }
        let chooseTag2 = [];
        $scope.chooseTwo = function (two, j) {
            data2[j] = !data2[j];
            chooseTag2 = [];
            for (let j = 0; j < data2.length; j++) {
                if (data2[j]) {
                    chooseTag2.push(tag2[j]);
                    $scope.musicData3 = $scope.music['第三层'];
                    tag3 = $scope.music['第三层'];
                }

            }
            console.log(chooseTag2);
            // console.log(tag3[0]);
        }


        let tag3 = $scope.music['第三层'];
        let data3 = new Array(tag3.length);
        $scope.data3 = data3;
        console.log(tag3.length);
        for (let k = 0; k < data3.length; k++) {

            data3[k] = false;

        }
        console.log(tag3.length);
        let chooseTag3 = [];
        $scope.chooseThree = function (three, k) {
            data3[k] = !data3[k];
            chooseTag3 = [];
            for (let k = 0; k < data3.length; k++) {
                if (data3[k]) {
                    chooseTag3.push(tag3[k]);
                    $scope.musicData4 = $scope.music['第四层'][tag3[k]];
                }

            }
            console.log(chooseTag3);
        }



        let chooseTag4 = [];
        $scope.chooseFour = function (four, l) {}


        $scope.SaveTag = function (songName) {
            let promise = MusicTagService.addTag(songName,chooseTag1,chooseTag2,chooseTag3,chooseTag4);
            promise.then(function (data) {
                console.log(data);
                swal('成功!', '添加成功', 'success');
            }, function (err) {
                swal({
                    title: '出错啦!',
                    text: err,
                    timer: 800,
                    type: 'error',
                    showConfirmButton: false
                }).catch(() => {
                });
            });


        }





    });




